package com.platform.comm.web.results;

import lombok.Data;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Description: Elasticsearch Search Result
 *
 * @author libin created on 2019/10/29
 */
@Data
public class EsSearchResult<T> {
    private long total = 0;
    private List<T> rows = new ArrayList<>();
    private String resourceKey;
    private Map<String, String> mapping = new LinkedHashMap<>();
    private List<Map<String, String>> columns = new ArrayList<>();

    public EsSearchResult() {
    }

    public EsSearchResult(List<T> rows, long total) {
        this();
        if (rows != null) {
            this.rows.addAll(rows);
        }
        this.total = total;
    }

    public EsSearchResult(List<T> rows, long total, Map<String, String> mapping, String resourceKey, List<Map<String, String>> columns) {
        this();
        if (rows != null) {
            this.rows.addAll(rows);
        }
        this.total = total;
        this.mapping.putAll(mapping);
        this.resourceKey = resourceKey;
        this.columns.addAll(columns);
    }

    public static <T> EsSearchResult<T> of() {
        return new EsSearchResult<>();
    }

    public static <T> EsSearchResult<T> of(List<T> rows, long total) {
        return new EsSearchResult<>(rows, total);
    }

    public <U> EsSearchResult<U> map(Function<? super T, ? extends U> converter) {
        return new EsSearchResult<>(this.rows.stream().map(converter).collect(Collectors.toList()), total, mapping, resourceKey, columns);
    }

    public void addRows(List<T> rows, long total) {
        this.rows.addAll(rows);
        this.total += total;
    }

    public void addMappings(Map<String, String> mapping) {
        if (Objects.nonNull(mapping) && !mapping.isEmpty()) {
            this.mapping.putAll(mapping);
        }
    }

    public void addMapping(String key, String value) {
        if (Objects.nonNull(key) && key.trim().length() > 0) {
            this.mapping.put(key, value);
        }
    }
}
